#include "list_stack.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

bool empty(struct list_stack *s)
{
    if(s->top == NULL)
        return true;
    return false;
}

bool push(struct list_stack *s, int value)
{
    struct node *new = malloc(sizeof(struct node));
    if (new == NULL){
        perror("malloc failed");
        return false;
    }
    new->data = value;
    new->next = NULL;

    if(s->top == NULL){
        s->top = new;
    }
    else{
        new->next = s->top;
        s->top = new;
    }

    return true;
}

bool pop(struct list_stack* s)
{
    if(empty(s)){
        printf("stack is empty\n");
        return false;
    }
    struct node *cur = s->top;
    s->top = s->top->next;
    free(cur);

    return true;
}

bool peek(struct list_stack *s, int *value)
{
    if(empty(s)){
        printf("stack is empty\n");
        return false;
    }
    *value = s->top->data;

    return true;
}

void show(struct list_stack *s)
{
    struct node *cur = s->top;
    while(cur != NULL){
        printf("%d ", cur->data);
        cur = cur->next;
    }
    printf("\n");
}

void clear(struct list_stack *s)
{
    struct node *cur = s->top;
    while(cur != NULL){
        cur = cur->next;
        free(s->top);
        s->top = cur;
    }
}

bool list_stack_init(struct list_stack *s)
{
    s->top = NULL;

    s->empty = empty;
    s->push = push;
    s->pop = pop;
    s->peek = peek;
    s->show = show;
    s->clear = clear;

    return true;
}
